package com.ds.robot.assistant.component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ds.robot.assistant.vo.User;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Component
@Slf4j
public class JsonFileReader {

    @Autowired
    private ResourceLoader resourceLoader;

    @Getter
    private Map<String, String> userName2IdMap;

    @PostConstruct
    public void init() {
        loadJsonFile();
    }

    private void loadJsonFile() {
        try {
            Resource resource = resourceLoader.getResource("classpath:demo/qx_userId.json");
            ObjectMapper objectMapper = new ObjectMapper();
            List<User> userList = objectMapper.readValue(resource.getInputStream(), new TypeReference<List<User>>() {
            });
            Assert.notEmpty(userList, "用户列表不能为空");
            // 原生方式
            // userMap = userList.stream().collect(HashMap::new, (m, v) -> m.put(v.getUserid(), v.getName()), HashMap::putAll);
            userName2IdMap = userList.stream().collect(Collectors.toMap(User::getName, User::getUserid, (oldVal, newVal) -> oldVal));
        } catch (IOException e) {
            log.error("加载用户列表失败", e);
        }
    }
}
